import sys
import re
import pandas as pd
import numpy as np
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                             QHBoxLayout, QPushButton, QLabel, QFileDialog, 
                             QMessageBox, QTableWidget, QTableWidgetItem, QHeaderView,
                             QProgressBar, QListWidget, QSplitter, QCheckBox, QComboBox,
                             QTabWidget)
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from PyQt5.QtGui import QFont, QColor, QBrush
import os
from datetime import datetime
import calendar
import glob

# ProcessThread 类定义 (从原始代码中复制)
class ProcessThread(QThread):
    progress = pyqtSignal(int)
    finished = pyqtSignal(list)
    error = pyqtSignal(str)
    
    def __init__(self, file_paths):
        super().__init__()
        self.file_paths = file_paths
        self.results = []
    
    def run(self):
        try:
            total_files = len(self.file_paths)
            for i, file_path in enumerate(self.file_paths):
                self.progress.emit(int((i / total_files) * 100))
                
                # 处理单个文件
                result = self.process_file(file_path)
                if result:
                    self.results.append(result)
            
            self.finished.emit(self.results)
        except Exception as e:
            self.error.emit(str(e))
    
    def process_file(self, file_path):
        try:
            # 从文件名提取信息
            filename = os.path.basename(file_path)
            year, month, area = self.extract_info_from_filename(filename)
            
            # 读取Excel文件
            try:
                # 尝试读取operationDetail工作表
                df = pd.read_excel(file_path, sheet_name='operationDetail')
            except:
                try:
                    # 尝试读取第一个工作表
                    df = pd.read_excel(file_path, sheet_name=0)
                except Exception as e:
                    raise Exception(f"无法读取Excel文件: {str(e)}")
            
            # 检查必要的列是否存在
            required_columns = ['理财经理', '上报日期', '培训', '活动', '沟通', '表彰', '其他']
            for col in required_columns:
                if col not in df.columns:
                    raise Exception(f'Excel文件中缺少必要的列: {col}')
            
            # 将上报日期转换为日期类型
            df['上报日期'] = pd.to_datetime(df['上报日期'])
            
            # 提取日期中的天数
            df['日期'] = df['上报日期'].dt.day
            
            # 计算每日总和
            df['每日总和'] = df[['培训', '活动', '沟通', '表彰', '其他']].sum(axis=1)
            
            # 按理财经理和日期分组并求和
            grouped = df.groupby(['理财经理', '日期'])['每日总和'].sum().reset_index()
            
            # 创建透视表 - 表1（带汇总）
            pivot_table1 = grouped.pivot_table(
                index='理财经理', 
                columns='日期', 
                values='每日总和', 
                fill_value=0,
                aggfunc='sum'
            )
            
            # 确保所有日期列都存在（1-31）
            all_days = list(range(1, 32))
            for day in all_days:
                if day not in pivot_table1.columns:
                    pivot_table1[day] = 0
            
            # 按日期排序列
            pivot_table1 = pivot_table1.reindex(sorted(pivot_table1.columns), axis=1)
            
            # 处理月份天数问题
            try:
                month_int = int(month)
                year_int = int(year) if year.isdigit() else datetime.now().year
                
                # 获取该月的实际天数
                _, days_in_month = calendar.monthrange(year_int, month_int)
                
                # 将超出实际天数的日期标记为N/A
                for day in range(days_in_month + 1, 32):
                    if day in pivot_table1.columns:
                        pivot_table1[day] = "N/A"
            except:
                # 如果无法确定月份，默认按31天处理
                pass
            
            # 将0值替换为空字符串
            for col in pivot_table1.columns:
                if pd.api.types.is_numeric_dtype(pivot_table1[col]):
                    pivot_table1[col] = pivot_table1[col].apply(
                        lambda x: "" if x == 0 else x
                    )
            
            # 添加总计行
            total_row = []
            for col in pivot_table1.columns:
                if pd.api.types.is_numeric_dtype(pivot_table1[col].iloc[0] if len(pivot_table1) > 0 else True):
                    # 计算数值列的总和，跳过空字符串
                    col_sum = sum(x for x in pivot_table1[col] if isinstance(x, (int, float)))
                    total_row.append(col_sum if col_sum != 0 else "")
                else:
                    total_row.append("N/A")
            
            pivot_table1.loc['总计'] = total_row
            
            # 创建表2（无汇总，大于等于1的替换为√）
            pivot_table2 = grouped.pivot_table(
                index='理财经理', 
                columns='日期', 
                values='每日总和', 
                fill_value=0,
                aggfunc='sum'
            )
            
            # 确保所有日期列都存在（1-31）
            for day in all_days:
                if day not in pivot_table2.columns:
                    pivot_table2[day] = 0
            
            # 按日期排序列
            pivot_table2 = pivot_table2.reindex(sorted(pivot_table2.columns), axis=1)
            
            # 处理月份天数问题
            try:
                month_int = int(month)
                year_int = int(year) if year.isdigit() else datetime.now().year
                
                # 获取该月的实际天数
                _, days_in_month = calendar.monthrange(year_int, month_int)
                
                # 将超出实际天数的日期标记为N/A
                for day in range(days_in_month + 1, 32):
                    if day in pivot_table2.columns:
                        pivot_table2[day] = "N/A"
            except:
                pass
            
            # 将大于等于1的值替换为√，0值替换为空字符串
            for col in pivot_table2.columns:
                if pd.api.types.is_numeric_dtype(pivot_table2[col]):
                    pivot_table2[col] = pivot_table2[col].apply(
                        lambda x: "√" if x >= 1 else ("" if x == 0 else "N/A")
                    )
                elif pd.api.types.is_object_dtype(pivot_table2[col]):
                    # 处理已经是字符串的列（如N/A）
                    pivot_table2[col] = pivot_table2[col].apply(
                        lambda x: x if x == "N/A" else ""
                    )
            
            return {
                'file_path': file_path,
                'filename': filename,
                'year': year,
                'month': month,
                'area': area,
                'data_table1': pivot_table1,  # 带汇总的表
                'data_table2': pivot_table2   # 无汇总，√标记的表
            }
            
        except Exception as e:
            self.error.emit(f"处理文件 {os.path.basename(file_path)} 时出错: {str(e)}")
            return None
    
    def extract_info_from_filename(self, filename):
        # 移除文件扩展名
        filename = os.path.splitext(filename)[0]
        
        # 使用多种模式尝试提取年份、月份和地区
        patterns = [
            r'(\d{4})年\s*(\S+?)\s*(\d{1,2})月',
            r'(\d{4})年\s*(\d{1,2})月\s*(\S+)',
            r'(\S+?)\s*(\d{4})年\s*(\d{1,2})月',
            r'(\d{4})-(\d{1,2})-(\S+)',
            r'(\S+)-(\d{4})-(\d{1,2})',
        ]
        
        for pattern in patterns:
            match = re.search(pattern, filename)
            if match:
                groups = match.groups()
                if len(groups) == 3:
                    if pattern == patterns[0]:
                        year, area, month = groups
                    elif pattern == patterns[1]:
                        year, month, area = groups
                    elif pattern == patterns[2]:
                        area, year, month = groups
                    elif pattern == patterns[3]:
                        year, month, area = groups
                    elif pattern == patterns[4]:
                        area, year, month = groups
                    
                    month = str(int(month)) if month.isdigit() else month
                    return year, month, area
        
        # 如果以上模式都不匹配，使用默认值
        year_match = re.search(r'(\d{4})', filename)
        year = year_match.group(1) if year_match else str(datetime.now().year)
        
        month_match = re.search(r'(\d{1,2})月', filename)
        if not month_match:
            month_match = re.search(r'[^0-9](\d{1,2})[^0-9]', filename)
        
        month = month_match.group(1) if month_match else str(datetime.now().month)
        month = str(int(month)) if month.isdigit() else month
        
        area_pattern = r'(北京|天津|上海|重庆|河北|山西|辽宁|吉林|黑龙江|江苏|浙江|安徽|福建|江西|山东|河南|湖北|湖南|广东|海南|四川|贵州|云南|陕西|甘肃|青海|台湾|内蒙古|广西|西藏|宁夏|新疆|香港|澳门)'
        area_match = re.search(area_pattern, filename)
        area = area_match.group(1) if area_match else "未知地区"
        
        return year, month, area

# 新增对比线程类
class CompareThread(QThread):
    progress = pyqtSignal(int)
    finished = pyqtSignal(list)
    error = pyqtSignal(str)
    
    def __init__(self, meeting_files, check_files):
        super().__init__()
        self.meeting_files = meeting_files
        self.check_files = check_files
        self.results = []
    
    def run(self):
        try:
            total_files = len(self.meeting_files)
            for i, meeting_file in enumerate(self.meeting_files):
                self.progress.emit(int((i / total_files) * 100))
                
                # 处理单个文件对比
                result = self.compare_files(meeting_file)
                if result:
                    self.results.append(result)
            
            self.finished.emit(self.results)
        except Exception as e:
            self.error.emit(str(e))
    
    def compare_files(self, meeting_file):
        try:
            # 从参会表文件名提取信息
            meeting_filename = os.path.basename(meeting_file)
            year, month, area = self.extract_info_from_filename(meeting_filename)
            
            # 查找对应的勾选表文件
            check_file_pattern = f"{year}年{month}月{area}机构银保打卡勾选表.xlsx"
            check_file = None
            
            for cf in self.check_files:
                if os.path.basename(cf) == check_file_pattern:
                    check_file = cf
                    break
            
            if not check_file:
                raise Exception(f"未找到对应的勾选表: {check_file_pattern}")
            
            # 读取参会表
            meeting_df = pd.read_excel(meeting_file, sheet_name=0)
            
            # 查找代理人名称和日期列
            agent_name_col = None
            date_cols = []
            
            for col in meeting_df.columns:
                if "代理人名称" in str(col):
                    agent_name_col = col
                elif "号" in str(col) and str(col).replace("号", "").isdigit():
                    date_cols.append(col)
            
            if not agent_name_col or not date_cols:
                raise Exception("参会表中未找到代理人名称或日期列")
            
            # 读取勾选表
            check_df = pd.read_excel(check_file, sheet_name=0)
            
            # 查找勾选表中的代理人名称和日期列
            check_agent_col = None
            check_date_cols = []
            
            for col in check_df.columns:
                if "代理人名称" in str(col):
                    check_agent_col = col
                elif "号" in str(col) and str(col).replace("号", "").isdigit():
                    check_date_cols.append(col)
            
            if not check_agent_col or not check_date_cols:
                raise Exception("勾选表中未找到代理人名称或日期列")
            
            # 创建对比结果DataFrame
            compare_result = meeting_df.copy()
            
            # 添加对比结果列
            for col in date_cols:
                compare_result[f"{col}_对比结果"] = ""
            
            # 进行对比
            for idx, meeting_row in meeting_df.iterrows():
                agent_name = meeting_row[agent_name_col]
                
                # 在勾选表中查找相同代理人
                check_row = check_df[check_df[check_agent_col] == agent_name]
                
                if check_row.empty:
                    # 未找到对应代理人，标记所有列为缺失
                    for col in date_cols:
                        compare_result.at[idx, f"{col}_对比结果"] = "缺失"
                    continue
                
                # 对比每个日期列
                for col in date_cols:
                    meeting_value = meeting_row[col]
                    check_value = check_row.iloc[0][col] if col in check_row.columns else None
                    
                    # 标准化值进行比较
                    meeting_std = self.standardize_value(meeting_value)
                    check_std = self.standardize_value(check_value) if check_value is not None else None
                    
                    if meeting_std != check_std:
                        compare_result.at[idx, f"{col}_对比结果"] = f"不一致(参会:{meeting_value},勾选:{check_value})"
                    else:
                        compare_result.at[idx, f"{col}_对比结果"] = "一致"
            
            return {
                'meeting_file': meeting_file,
                'check_file': check_file,
                'filename': meeting_filename,
                'year': year,
                'month': month,
                'area': area,
                'compare_result': compare_result
            }
            
        except Exception as e:
            self.error.emit(f"对比文件 {os.path.basename(meeting_file)} 时出错: {str(e)}")
            return None
    
    def standardize_value(self, value):
        """标准化单元格值以便比较"""
        if pd.isna(value) or value == "" or value is None:
            return "空"
        elif str(value).strip() in ["√", "✓", "对", "是"]:
            return "出勤"
        elif str(value).strip() in ["☆", "★", "年"]:
            return "年假"
        elif str(value).strip() in ["●", "事"]:
            return "事假"
        elif str(value).strip() in ["○", "病"]:
            return "病假"
        elif str(value).strip() in ["X", "×", "旷"]:
            return "旷工"
        elif str(value).strip() in ["△", "迟"]:
            return "迟到/早退"
        else:
            return str(value).strip()
    
    def extract_info_from_filename(self, filename):
        # 移除文件扩展名
        filename = os.path.splitext(filename)[0]
        
        # 使用多种模式尝试提取年份、月份和地区
        patterns = [
            r'(\d{4})年\s*(\S+?)\s*(\d{1,2})月',
            r'(\d{4})年\s*(\d{1,2})月\s*(\S+)',
            r'(\S+?)\s*(\d{4})年\s*(\d{1,2})月',
            r'(\d{4})-(\d{1,2})-(\S+)',
            r'(\S+)-(\d{4})-(\d{1,2})',
        ]
        
        for pattern in patterns:
            match = re.search(pattern, filename)
            if match:
                groups = match.groups()
                if len(groups) == 3:
                    if pattern == patterns[0]:
                        year, area, month = groups
                    elif pattern == patterns[1]:
                        year, month, area = groups
                    elif pattern == patterns[2]:
                        area, year, month = groups
                    elif pattern == patterns[3]:
                        year, month, area = groups
                    elif pattern == patterns[4]:
                        area, year, month = groups
                    
                    month = str(int(month)) if month.isdigit() else month
                    return year, month, area
        
        # 如果以上模式都不匹配，使用默认值
        year_match = re.search(r'(\d{4})', filename)
        year = year_match.group(1) if year_match else str(datetime.now().year)
        
        month_match = re.search(r'(\d{1,2})月', filename)
        if not month_match:
            month_match = re.search(r'[^0-9](\d{1,2})[^0-9]', filename)
        
        month = month_match.group(1) if month_match else str(datetime.now().month)
        month = str(int(month)) if month.isdigit() else month
        
        area_pattern = r'(北京|天津|上海|重庆|河北|山西|辽宁|吉林|黑龙江|江苏|浙江|安徽|福建|江西|山东|河南|湖北|湖南|广东|海南|四川|贵州|云南|陕西|甘肃|青海|台湾|内蒙古|广西|西藏|宁夏|新疆|香港|澳门)'
        area_match = re.search(area_pattern, filename)
        area = area_match.group(1) if area_match else "未知地区"
        
        return year, month, area

# 修改主窗口类，添加对比功能
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # 初始化所有文件路径列表
        self.file_paths = []
        self.meeting_file_paths = []  # 新增：参会表文件路径列表
        self.check_file_paths = []    # 新增：勾选表文件路径列表
        self.results = []
        self.compare_results = []
        self.current_table_type = 1  # 1: 表1, 2: 表2
        self.current_mode = "process"  # process 或 compare
        self.initUI()
        
    def initUI(self):
        self.setWindowTitle('机构银保打卡工具 - 生成与对比')
        self.setGeometry(100, 100, 1200, 800)
        
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        layout = QVBoxLayout()
        central_widget.setLayout(layout)
        
        # 创建标签页
        self.tab_widget = QTabWidget()
        self.process_tab = QWidget()
        self.compare_tab = QWidget()
        
        self.tab_widget.addTab(self.process_tab, "生成勾选表")
        self.tab_widget.addTab(self.compare_tab, "对比参会表与勾选表")
        
        layout.addWidget(self.tab_widget)
        
        # 设置生成标签页
        self.setup_process_tab()
        # 设置对比标签页
        self.setup_compare_tab()
        
    def setup_process_tab(self):
        layout = QVBoxLayout(self.process_tab)
        
        # 文件选择区域
        file_layout = QHBoxLayout()
        self.file_list = QListWidget()
        self.file_list.setMaximumHeight(100)
        
        self.select_btn = QPushButton('添加Excel文件')
        self.select_btn.clicked.connect(self.select_files)
        
        self.clear_btn = QPushButton('清空列表')
        self.clear_btn.clicked.connect(self.clear_file_list)
        
        file_btn_layout = QVBoxLayout()
        file_btn_layout.addWidget(self.select_btn)
        file_btn_layout.addWidget(self.clear_btn)
        
        file_layout.addWidget(self.file_list, 3)
        file_layout.addLayout(file_btn_layout, 1)
        
        # 处理按钮区域
        self.process_btn = QPushButton('处理数据')
        self.process_btn.clicked.connect(self.process_data)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        
        # 导出按钮区域
        export_layout = QHBoxLayout()
        self.export_btn1 = QPushButton('导出汇总表（表1）')
        self.export_btn1.clicked.connect(lambda: self.export_result(1))
        self.export_btn1.setEnabled(False)
        
        self.export_btn2 = QPushButton('导出勾选表（表2）')
        self.export_btn2.clicked.connect(lambda: self.export_result(2))
        self.export_btn2.setEnabled(False)
        
        export_layout.addWidget(self.export_btn1)
        export_layout.addWidget(self.export_btn2)
        
        # 结果显示区域
        result_splitter = QSplitter(Qt.Vertical)
        
        # 结果列表和表格选择
        result_top_layout = QHBoxLayout()
        result_top_widget = QWidget()
        result_top_widget.setLayout(result_top_layout)
        
        self.result_list = QListWidget()
        self.result_list.currentRowChanged.connect(self.show_result)
        
        # 表格类型选择
        table_type_layout = QVBoxLayout()
        table_type_label = QLabel("查看表格类型:")
        self.table_type_combo = QComboBox()
        self.table_type_combo.addItems(["汇总表（带总计）", "勾选表（√标记）"])
        self.table_type_combo.currentIndexChanged.connect(self.change_table_type)
        
        table_type_layout.addWidget(table_type_label)
        table_type_layout.addWidget(self.table_type_combo)
        table_type_layout.addStretch()
        
        result_top_layout.addWidget(self.result_list, 3)
        result_top_layout.addLayout(table_type_layout, 1)
        
        # 结果表格
        self.table = QTableWidget()
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        
        result_splitter.addWidget(result_top_widget)
        result_splitter.addWidget(self.table)
        result_splitter.setSizes([100, 500])
        
        layout.addLayout(file_layout)
        layout.addWidget(self.process_btn)
        layout.addWidget(self.progress_bar)
        layout.addLayout(export_layout)
        layout.addWidget(result_splitter)
        
    def setup_compare_tab(self):
        layout = QVBoxLayout(self.compare_tab)
        
        # 文件选择区域
        compare_file_layout = QHBoxLayout()
        
        # 参会表选择
        meeting_layout = QVBoxLayout()
        meeting_label = QLabel("参会表文件:")
        self.meeting_list = QListWidget()
        self.meeting_list.setMaximumHeight(80)
        self.select_meeting_btn = QPushButton('添加参会表')
        self.select_meeting_btn.clicked.connect(self.select_meeting_files)
        
        meeting_layout.addWidget(meeting_label)
        meeting_layout.addWidget(self.meeting_list)
        meeting_layout.addWidget(self.select_meeting_btn)
        
        # 勾选表选择
        check_layout = QVBoxLayout()
        check_label = QLabel("勾选表文件:")
        self.check_list = QListWidget()
        self.check_list.setMaximumHeight(80)
        self.select_check_btn = QPushButton('添加勾选表')
        self.select_check_btn.clicked.connect(self.select_check_files)
        
        check_layout.addWidget(check_label)
        check_layout.addWidget(self.check_list)
        check_layout.addWidget(self.select_check_btn)
        
        compare_file_layout.addLayout(meeting_layout)
        compare_file_layout.addLayout(check_layout)
        
        # 对比按钮区域
        self.compare_btn = QPushButton('开始对比')
        self.compare_btn.clicked.connect(self.compare_data)
        
        # 进度条
        self.compare_progress_bar = QProgressBar()
        self.compare_progress_bar.setVisible(False)
        
        # 导出按钮区域
        compare_export_layout = QHBoxLayout()
        self.export_compare_btn = QPushButton('导出对比结果')
        self.export_compare_btn.clicked.connect(self.export_compare_result)
        self.export_compare_btn.setEnabled(False)
        
        compare_export_layout.addWidget(self.export_compare_btn)
        
        # 对比结果显示区域
        compare_result_splitter = QSplitter(Qt.Vertical)
        
        # 结果列表
        compare_result_top_layout = QHBoxLayout()
        compare_result_top_widget = QWidget()
        compare_result_top_widget.setLayout(compare_result_top_layout)
        
        self.compare_result_list = QListWidget()
        self.compare_result_list.currentRowChanged.connect(self.show_compare_result)
        
        compare_result_top_layout.addWidget(self.compare_result_list)
        
        # 对比结果表格
        self.compare_table = QTableWidget()
        self.compare_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        
        compare_result_splitter.addWidget(compare_result_top_widget)
        compare_result_splitter.addWidget(self.compare_table)
        compare_result_splitter.setSizes([100, 500])
        
        layout.addLayout(compare_file_layout)
        layout.addWidget(self.compare_btn)
        layout.addWidget(self.compare_progress_bar)
        layout.addLayout(compare_export_layout)
        layout.addWidget(compare_result_splitter)
    
    def select_files(self):
        file_paths, _ = QFileDialog.getOpenFileNames(
            self, '选择Excel文件', '', 'Excel files (*.xlsx *.xls)')
        
        if file_paths:
            for file_path in file_paths:
                if file_path not in self.file_paths:
                    self.file_paths.append(file_path)
                    self.file_list.addItem(os.path.basename(file_path))
            
            self.process_btn.setEnabled(len(self.file_paths) > 0)
    
    def clear_file_list(self):
        self.file_paths.clear()
        self.file_list.clear()
        self.process_btn.setEnabled(False)
    
    def select_meeting_files(self):
        file_paths, _ = QFileDialog.getOpenFileNames(
            self, '选择参会表文件', '', 'Excel files (*.xlsx *.xls)')
        
        if file_paths:
            for file_path in file_paths:
                if file_path not in self.meeting_file_paths:
                    self.meeting_file_paths.append(file_path)
                    self.meeting_list.addItem(os.path.basename(file_path))
            
            self.compare_btn.setEnabled(len(self.meeting_file_paths) > 0 and len(self.check_file_paths) > 0)
    
    def select_check_files(self):
        file_paths, _ = QFileDialog.getOpenFileNames(
            self, '选择勾选表文件', '', 'Excel files (*.xlsx *.xls)')
        
        if file_paths:
            for file_path in file_paths:
                if file_path not in self.check_file_paths:
                    self.check_file_paths.append(file_path)
                    self.check_list.addItem(os.path.basename(file_path))
            
            self.compare_btn.setEnabled(len(self.meeting_file_paths) > 0 and len(self.check_file_paths) > 0)
    
    def process_data(self):
        if not self.file_paths:
            QMessageBox.warning(self, '警告', '请先选择Excel文件')
            return
        
        self.progress_bar.setVisible(True)
        self.process_btn.setEnabled(False)
        
        # 创建工作线程处理数据
        self.thread = ProcessThread(self.file_paths)
        self.thread.progress.connect(self.update_progress)
        self.thread.finished.connect(self.process_finished)
        self.thread.error.connect(self.process_error)
        self.thread.start()
    
    def compare_data(self):
        if not self.meeting_file_paths or not self.check_file_paths:
            QMessageBox.warning(self, '警告', '请先选择参会表和勾选表文件')
            return
        
        self.compare_progress_bar.setVisible(True)
        self.compare_btn.setEnabled(False)
        
        # 创建对比线程
        self.compare_thread = CompareThread(self.meeting_file_paths, self.check_file_paths)
        self.compare_thread.progress.connect(self.update_compare_progress)
        self.compare_thread.finished.connect(self.compare_finished)
        self.compare_thread.error.connect(self.compare_error)
        self.compare_thread.start()
    
    def update_progress(self, value):
        self.progress_bar.setValue(value)
    
    def update_compare_progress(self, value):
        self.compare_progress_bar.setValue(value)
    
    def process_finished(self, results):
        self.results = results
        self.progress_bar.setVisible(False)
        self.process_btn.setEnabled(True)
        self.export_btn1.setEnabled(len(results) > 0)
        self.export_btn2.setEnabled(len(results) > 0)
        
        # 更新结果列表
        self.result_list.clear()
        for result in results:
            display_text = f"{result['year']}年{result['month']}月{result['area']} - {os.path.basename(result['file_path'])}"
            self.result_list.addItem(display_text)
        
        if results:
            self.result_list.setCurrentRow(0)
        
        QMessageBox.information(self, '完成', f'成功处理 {len(results)} 个文件')
    
    def compare_finished(self, results):
        self.compare_results = results
        self.compare_progress_bar.setVisible(False)
        self.compare_btn.setEnabled(True)
        self.export_compare_btn.setEnabled(len(results) > 0)
        
        # 更新对比结果列表
        self.compare_result_list.clear()
        for result in results:
            display_text = f"{result['year']}年{result['month']}月{result['area']} - {os.path.basename(result['meeting_file'])}"
            self.compare_result_list.addItem(display_text)
        
        if results:
            self.compare_result_list.setCurrentRow(0)
        
        QMessageBox.information(self, '完成', f'成功对比 {len(results)} 个文件')
    
    def process_error(self, error_msg):
        self.progress_bar.setVisible(False)
        self.process_btn.setEnabled(True)
        QMessageBox.critical(self, '错误', error_msg)
    
    def compare_error(self, error_msg):
        self.compare_progress_bar.setVisible(False)
        self.compare_btn.setEnabled(True)
        QMessageBox.critical(self, '错误', error_msg)
    
    def change_table_type(self, index):
        self.current_table_type = index + 1  # 1: 表1, 2: 表2
        current_row = self.result_list.currentRow()
        if current_row >= 0:
            self.show_result(current_row)
    
    def show_result(self, index):
        if index < 0 or index >= len(self.results):
            return
        
        result = self.results[index]
        
        # 根据选择的表格类型显示不同的数据
        if self.current_table_type == 1:
            pivot_table = result['data_table1']  # 汇总表
        else:
            pivot_table = result['data_table2']  # 勾选表
        
        # 设置表格行数和列数
        self.table.setRowCount(pivot_table.shape[0])
        self.table.setColumnCount(pivot_table.shape[1] + 1)
        
        # 设置表头
        self.table.setHorizontalHeaderItem(0, QTableWidgetItem("代理人名称"))
        for i, day in enumerate(pivot_table.columns, 1):
            self.table.setHorizontalHeaderItem(i, QTableWidgetItem(f"{day}号"))
        
        # 填充数据
        for i, (index_name, row) in enumerate(pivot_table.iterrows()):
            # 第一列显示理财经理名称
            self.table.setItem(i, 0, QTableWidgetItem(str(index_name)))
            
            # 填充每日数据
            for j, value in enumerate(row, 1):
                # 如果值为空字符串，显示空单元格
                if value == "":
                    item = QTableWidgetItem("")
                else:
                    item = QTableWidgetItem(str(value))
                
                # 特殊处理单元格样式
                if str(value) == "N/A":
                    item.setBackground(QColor(240, 240, 240))
                    item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                elif str(value) == "√":
                    item.setBackground(QColor(220, 255, 220))  # 浅绿色背景
                    item.setTextAlignment(Qt.AlignCenter)
                    item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                
                self.table.setItem(i, j, item)
        
        # 如果是汇总表，设置总计行为粗体
        if self.current_table_type == 1 and pivot_table.shape[0] > 0:
            for j in range(self.table.columnCount()):
                item = self.table.item(self.table.rowCount()-1, j)
                if item and item.text():
                    font = QFont()
                    font.setBold(True)
                    item.setFont(font)
    
    def show_compare_result(self, index):
        if index < 0 or index >= len(self.compare_results):
            return
        
        result = self.compare_results[index]
        compare_df = result['compare_result']
        
        # 设置表格行数和列数
        self.compare_table.setRowCount(compare_df.shape[0])
        self.compare_table.setColumnCount(compare_df.shape[1])
        
        # 设置表头
        for j, col in enumerate(compare_df.columns):
            self.compare_table.setHorizontalHeaderItem(j, QTableWidgetItem(str(col)))
        
        # 填充数据
        for i, row in compare_df.iterrows():
            for j, value in enumerate(row):
                item = QTableWidgetItem(str(value))
                
                # 标记不一致的单元格
                if "_对比结果" in str(compare_df.columns[j]) and "不一致" in str(value):
                    item.setBackground(QColor(255, 200, 200))  # 浅红色背景
                elif "_对比结果" in str(compare_df.columns[j]) and "一致" in str(value):
                    item.setBackground(QColor(200, 255, 200))  # 浅绿色背景
                elif "_对比结果" in str(compare_df.columns[j]) and "缺失" in str(value):
                    item.setBackground(QColor(255, 220, 180))  # 浅橙色背景
                
                self.compare_table.setItem(i, j, item)
    
    def export_result(self, table_type):
        if not self.results:
            QMessageBox.warning(self, '警告', '没有可导出的数据')
            return
        
        # 选择导出文件夹
        export_dir = QFileDialog.getExistingDirectory(self, '选择导出文件夹')
        
        if not export_dir:
            return
        
        try:
            success_count = 0
            
            # 创建子文件夹
            if table_type == 1:
                output_dir = os.path.join(export_dir, "汇总表")
                folder_name = "汇总表"
            else:
                output_dir = os.path.join(export_dir, "勾选表")
                folder_name = "勾选表"
            
            os.makedirs(output_dir, exist_ok=True)
            
            for result in self.results:
                # 选择要导出的数据
                if table_type == 1:
                    data = result['data_table1']
                    file_suffix = "汇总表"
                else:
                    data = result['data_table2']
                    file_suffix = "勾选表"
                
                # 生成文件名
                filename = f"{result['year']}年{result['month']}月{result['area']}机构银保打卡{file_suffix}.xlsx"
                file_path = os.path.join(output_dir, filename)
                
                # 创建一个新的DataFrame，添加代理人名称列
                export_df = data.reset_index()
                export_df.rename(columns={'index': '代理人名称'}, inplace=True)
                
                # 修改列名为"x号"格式
                new_columns = ['代理人名称']
                for col in export_df.columns[1:]:
                    if isinstance(col, int):
                        new_columns.append(f"{col}号")
                    else:
                        new_columns.append(col)
                
                export_df.columns = new_columns
                
                # 保存到Excel
                export_df.to_excel(file_path, index=False)
                success_count += 1
            
            QMessageBox.information(self, '成功', f'成功导出 {success_count} 个文件到: {export_dir}/{folder_name}')
            
        except Exception as e:
            QMessageBox.critical(self, '错误', f'保存文件时发生错误: {str(e)}')
    
    def export_compare_result(self):
        if not self.compare_results:
            QMessageBox.warning(self, '警告', '没有可导出的对比结果')
            return
        
        # 选择导出文件夹
        export_dir = QFileDialog.getExistingDirectory(self, '选择导出文件夹')
        
        if not export_dir:
            return
        
        try:
            success_count = 0
            output_dir = os.path.join(export_dir, "对比结果")
            os.makedirs(output_dir, exist_ok=True)
            
            for result in self.compare_results:
                # 生成文件名
                filename = f"{result['year']}年{result['month']}月{result['area']}参会勾选对比结果.xlsx"
                file_path = os.path.join(output_dir, filename)
                
                # 保存对比结果到Excel
                result['compare_result'].to_excel(file_path, index=False)
                success_count += 1
            
            QMessageBox.information(self, '成功', f'成功导出 {success_count} 个对比结果文件到: {export_dir}/对比结果')
            
        except Exception as e:
            QMessageBox.critical(self, '错误', f'保存对比结果时发生错误: {str(e)}')

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()